package model.skill;

import java.util.HashSet;
import java.util.Set;

import model.Executable;
import model.GameClock;
import model.effect.Effect;
import model.handler.MovementHandler;
import model.map.Direction;
import model.map.GameMap;
import model.map.Location;
import model.map.LocationProjection;
import model.map.World;
import utilities.*;

/**
 * A propagation that returns the location it starts on.
 */
public class SelfProjectile extends Projectile implements Archiveable {
	
	/**
	 * @param startLocation
	 */
	
	private Location startLocation;
	private SelfProjectile self = this;
	private int counter = 1; 
	
	public SelfProjectile(String name, Effect effect, LocationProjection propagationLogic, int speed)
	{
		super(name, effect, propagationLogic, 0, speed);
	}

	public SelfProjectile() {
		// TODO Auto-generated constructor stub
	}

	public void propagate(ProjectileInformation projectileInfo)
	{
		final Location startLocation = projectileInfo.getLocation();
		final GameClock c = GameClock.getInstance();
		final GameMap gameMap = World.getInstance().getCurrentMap();
		final int propagateSpeed = this.getSpeed();
		
		Executable exec = new Executable()
		{
			public void execute()
			{
				gameMap.addProjectile(startLocation, self);
				if(gameMap.hasEntity(startLocation))
				{
					self.getEffect().doEffect(gameMap.getEntity(startLocation));
				}
				
				c.schedule(propagateSpeed, new Executable() {
					public void execute() 
					{	
						if(gameMap.hasProjectile(startLocation))
							{
								gameMap.removeProjectile(startLocation);
							}
					}
				});
			}
		};
		exec.execute();
	}
	
	public Archive save() {
		Archive archive = super.save();
		
		archive.putAttribute("counter", Integer.toString(this.counter));
		
		archive.putClassName("startLocation", this.startLocation.getClass().getName());
		archive.putOneRelationship("startLocation", this.startLocation);
		
		return archive;
	}
	
	public void load(Archive archive) {
		super.load(archive);
		
		this.counter = Integer.parseInt(archive.getAttribute("counter"));
		
		this.startLocation = (Location)ModelFactory.getInstance().createInstanceWithClassName(archive.getClassName("startLocation"));
		this.startLocation.load(archive.getOneRelationship("startLocation"));
	}
}
